import { Message } from 'element-ui'
import utils from '@/assets/utils'
export default ({app})=> {
  const myList = ['/supply', '/company', '/account']

  app.router.beforeEach((to, from, next) => {
    // console.log(to)
    // NProgress.start()
    var token = utils.getCookies('token')
    if (token) {
      if (to.path === '/login' || to.path === '/register') {
        next({ path: '/' })
        // NProgress.done()
      } else {
        if (myList.indexOf(to.path) !== -1) {
          $nuxt.$store.dispatch('IsCheck')
        }
        const mobile = $nuxt.$store.state.user.mobile
        if (!mobile) {
          $nuxt.$store.dispatch('GetInfo').then(res => { // 拉取user_info
            const data = res.data.data
            const resources = data.resources
            $nuxt.$store.dispatch('GenerateRoutes', resources).then(() => { // 根据roles权限生成可访问的路由表
              app.router.addRoutes($nuxt.$store.getters.addRouters) // 动态添加可访问路由表
              next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
            })
            // next()
          }).catch(err => {
            $nuxt.$store.dispatch('FedLogOut').then(() => {
              Message.error(err || '认证失败，请重新登录')
              next({ path: '/' })
            })
          })
        } else {
          next()
        }
      }
    } else {
      next()
    }
  })

  app.router.afterEach((to, from) => {
    // NProgress.done()
    // if (to.path === '/financialInfo/detail' && to.query.flag) {
    //   window.scrollTo(0, 680)
    // } else {
    //   window.scrollTo(0, 0)
    // }
  })
}